<template>
  <div id="single-choice"
       class="task-single-choice">
    <!-- 每个单选 -->
    <div class="task-single-main"
         :id="'program'+opIndex"
         v-for="(option,opIndex) in FormData.programmingData"
         :key="opIndex">
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span v-if="option.isEdit"> {{opIndex+1}}.请为本题目选择编程题并设置分数</span>
          <div style="width:470px;float:left;" v-if="!option.isEdit">{{opIndex+1}}.{{option.programmingQuestionInfo.title}}({{option.score}}分) </div>
          <div style="float: right; margin-top:-5px;">
            <el-button-group style="float: right;">
              <el-button icon="el-icon-edit" @click="isEditStatus(option)"></el-button>
              <el-button icon="el-icon-delete" @click="deleteQuestion(FormData.programmingData, option, opIndex)"></el-button>
              <el-button icon="el-icon-arrow-up" @click="moveQuestion(FormData, opIndex, 'up')"></el-button>
              <el-button icon="el-icon-arrow-down" @click="moveQuestion(FormData, opIndex, 'down')"></el-button>
            </el-button-group>
            <el-input style="width:35%;float: right;" v-if="option.isEdit" size="mid" placeholder="请输入分数" v-model.number="option.score" @input="scoreInput($event, option, opIndex)" @blur="checkRequired($event)">
              <template slot="prepend">分数</template>
            </el-input>
          </div>
        </div>
        <div v-if="!option.isEdit" v-html="option.programmingQuestionInfo.description" class="problemDescription"></div>
        <div v-if="!option.isEdit">
          <el-card shadow="never" v-if="option.programmingQuestionId != -1" :padding="20" id="submit-code" style="border:transparent;">
            <CodeMirror :value.sync="code"
                        :theme="theme"
                        :languages="option.programmingQuestionInfo.languages"
                        :language="language"></CodeMirror>
          </el-card>
        </div>
        <el-collapse-transition>
          <div class="task-single-design design" v-show="option.isEdit">
            <div class="task-single-design-options-div">
              <div class="task-single-design-options-box">
                <el-table
                  :data = "questions"
                  style ="width: 100%;"
                  stripe>
                  <el-table-column
                    prop="title"
                    :label="$t('m.Title')"/>
                  <el-table-column
                    prop = "difficulty"
                    :label="$t('m.Difficulty')"
                    width="80px"/>
                  <el-table-column
                    prop="description"
                    :label="$t('m.Description')"/>
                  <el-table-column
                    label="操作"
                    width="90px">
                    <template slot-scope="scope">
                      <el-button size="small" @click="handleClick(scope.row,option)">添加</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </el-collapse-transition>
      </el-card>
      <div class="hr" v-if="opIndex!=FormData.programmingData.length-1"/></div>
  </div>
</template>

<script>
import api from '../../../../../api'
import CodeMirror from '../../../../../../oj/components/AddCodeMirror.vue'

export default {
  name: 'Program-choice',
  props: ['FormData'],
  components: {
    CodeMirror
  },
  data () {
    return {
      visible: false,
      visible2: [],
      questions: [],
      code: '',
      theme: 'solarized',
      type: 'Homework',
      language: ''
    }
  },
  mounted () {
    this.FormData.programmingData.forEach(_ => {
      this.visible2.push(false)
    })
    let params = {
      limit: 1000000  // 拿到数据的页面，处理分页
    }
    let diffStr = []
    diffStr['xHigh'] = '大师'
    diffStr['High'] = '困难'
    diffStr['Mid'] = '中等'
    diffStr['Low'] = '普通'
    diffStr['xLow'] = '简单'
    api.getProblemList(params).then(res => {
      this.questions = res.data.data.results
      this.questions.forEach(element => {
        let type = element.difficulty
        element.difficulty = diffStr[type]  // 难度显示中文
        element.description = element.description.replace(/<\/?.+?>/g, '') // 去掉描述中的html标签
      })
    })
  },
  methods: {
    async scoreInput (e, option, opIndex) {
      var s = 0
      var m = 0
      var j = 0
      var p = 0
      await this.FormData.singleData.forEach(_ => {
        s += (_.score)
      })
      await this.FormData.multipleData.forEach(_ => {
        m += (_.score)
      })
      await this.FormData.judgeData.forEach(_ => {
        j += (_.score)
      })
      await this.FormData.programmingData.forEach(_ => {
        p += (_.score)
      })
      this.FormData.totalScore = await (s + m + j + p)
    },
    checkRequired (e) {
      if (!e.target.value) {
        this.$message({
          message: '请填写题目分数',
          type: 'warning'
        })
        this.FormData.required = false
      } else {
        this.FormData.required = true
      }
    },
    moveOption (ArrayData, index, type) {
      const options = {
        up: () => {
          if (index === 0) {
            this.$message.warning('已经是第一个了，没法再向上移动了！')
            return
          }
          this.swapArray(ArrayData, index, index - 1)
        },
        down: () => {
          if (index + 1 === ArrayData.length) {
            this.$message.warning('已经是最后一题个，没法再向下移动了')
            return
          }
          this.swapArray(ArrayData, index, index + 1)
        }
      }
      options[type]()
    },
    isEditStatus (option) {
      option.isEdit = !option.isEdit
    },
    // 导入题库
    importQuestionBank (option, opIndex) {
    },
    deleteQuestion (ArrayData, option, opIndex) {
      if (this.FormData.homework_id && option.programmingQuestionId) {
        api['deleteProblemInHomework'](this.FormData.homework_id, option.programmingQuestionId).then(res => {
          // 删除题目，重置分数
          ArrayData.splice(opIndex, 1)
          this.scoreInput()
        }).catch((e) => {
        })
      } else {
        // 未提交的题目，进行页面上的删除
        ArrayData.splice(opIndex, 1)
        this.scoreInput()
      }
    },
    // 移动 点击的题 的位置
    // arr 点击的位置 移动的方式
    moveQuestion (ArrayData, singleIndex, type) {
      const options = {
        'down': () => {
          if (singleIndex + 1 === ArrayData.programmingData.length) {
            this.$message.warning('已经是最后一题个，没法再向下移动了')
            return
          }
          this.swapArray(ArrayData.programmingData, singleIndex, singleIndex + 1)
          setTimeout(() => {
            document.getElementById('program' + (singleIndex + 1)).scrollIntoView({ block: 'start', behavior: 'smooth' })
          }, 200)
        },
        'up': () => {
          if (singleIndex === 0) {
            this.$message.warning('已经是第一个了，没法再向上移动了！')
            return
          }
          this.swapArray(ArrayData.programmingData, singleIndex, singleIndex - 1)
          setTimeout(() => {
            document.getElementById('program' + (singleIndex - 1)).scrollIntoView({ block: 'start', behavior: 'smooth' })
          }, 200)
        }
      }
      options[type]()
    },
    swapArray (arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0]
    },
    // 创建和修改程序设计题
    handleClick (row, option) {
      if (!option.score) {
        this.$message({
          message: '请填写题目分数',
          type: 'error'
        })
      } else {
        let oldProblemId = option.programmingQuestionId
        if (oldProblemId) {
          let passData = {
            oldProblemId: oldProblemId,
            newProblemId: row.id,
            homeworkId: this.FormData.homework_id,
            score: option.score
          }
          // 修改程序设计题
          api['updateHomeworkAndProblem'](passData).then(res => {
            // 修改信息
            console.log(option)
            option.programmingQuestionId = row.id
            option.programmingQuestionInfo = row
            option.isEdit = false
            this.updateHomeworkScore()
          }).catch((e) => {
          })
        } else {
          let passData = {
            problemId: row.id,
            homeworkId: this.FormData.homework_id,
            score: option.score
          }
          // 添加程序设计题和作业间的关系
          api['matchHomeworkAndProblem'](passData).then(res => {
            // 修改信息
            option.programmingQuestionId = row.id
            option.programmingQuestionInfo = row
            option.isEdit = false
            this.updateHomeworkScore()
          }).catch((e) => {
          })
        }
      }
    },
    updateHomeworkScore () {
      let passData = {
        section_id: this.FormData.sectionId,
        homeworkId: this.FormData.homework_id,
        title: this.FormData.title,
        selection_problems: this.FormData.selections,
        score: this.FormData.totalScore
      }
      api['updateHomework'](passData).then(res => {
      }).catch((e) => {
      })
    },
    onResetToTemplate () {
      this.$Modal.confirm({
        content: this.$i18n.t('m.Are_you_sure_you_want_to_reset_your_code'),
        onOk: () => {
          let template = this.problem.template
          if (template && template[this.language]) {
            this.code = template[this.language]
          } else {
            this.code = ''
          }
        }
      })
    },
    SubmitCode () {
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin-top: 20px;
  margin-bottom: 20px;
  width: 100%;
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #E4E7ED;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
  line-height: 36px;
  text-align:center;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.problemDescription {
  font-size: 15px;
  margin: 0 0 0 20px;
}
</style>
